﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using web.core.Models;
using web.core.ViewModels;
using System.Web.UI;
using System.Xml;
//using iTextSharp.text;
//using iTextSharp.text.xml;
//using iTextSharp.text.pdf;
using System.IO;
using System.Text;
using web.bussines;
using web.data.entities;
using web.component;

namespace web.core.Controllers
{
    public class baseController : Controller
    {
        #region select list common
        public List<SelectListItem> GetSizePagingPublic(int selectedValue){
            List<SelectListItem> sizeDrop = new List<SelectListItem>();
            sizeDrop.AddRange(new SelectListItem[] { 
                            new SelectListItem{Selected=selectedValue==10?true:false, Text = "10", Value = "10" },
                            new SelectListItem{Selected=selectedValue==25?true:false, Text = "25", Value = "25" },
                            new SelectListItem{Selected=selectedValue==50?true:false, Text = "50", Value = "50" },
                            new SelectListItem{Selected=selectedValue==100?true:false, Text = "100", Value = "100" }
                        });
            return sizeDrop;
        } 
        #endregion

        #region upload image

        /// <summary>
        /// upload image in admin page
        /// </summary>
        /// <param name="is_del">delete or not?</param>
        /// <param name="cur_name">current value: for case update</param>
        /// <param name="type">type of image</param>
        /// <param name="lblAnh">literal to display image</param>
        /// <param name="control">upload control</param>
        /// <returns></returns>
        public static string SaveImage(bool is_del, string cur_name, HttpPostedFileBase control, admin_const.E_IMG_TYPE type, admin_const.E_IMG_THUMB thumb_type)
        {
            ////---------------------
            //foreach (string file in Request.Files)
            //{
            //    HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
            //    if (hpf.ContentLength == 0)
            //        continue;
            //    string savedFileName = Path.Combine(
            //       AppDomain.CurrentDomain.BaseDirectory,
            //       Path.GetFileName(hpf.FileName));
            //    hpf.SaveAs(savedFileName);

            //    r.Add(new ViewDataUploadFilesResult()
            //    {
            //        Name = savedFileName,
            //        Length = hpf.ContentLength
            //    });
            //}
            ////---------------------
            //// Verify that the user selected a file
            //if (control != null && control.ContentLength > 0)
            //{
            //    // extract only the fielname
            //    var fileName = Path.GetFileName(file.FileName);
            //    // store the file inside ~/App_Data/uploads folder
            //    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
            //    file.SaveAs(path);
            //}
            ////---------------------

            try
            {
                string retimg = "";

                //if (control.FileName != "")
                if (control != null && control.ContentLength > 0)
                {
                    //locate image file
                    string imagePathTemp = "";
                    if (type == admin_const.E_IMG_TYPE.CATALOG)
                    {
                        imagePathTemp = "catalog/" +
                           DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Year + DateTime.Now.Hour + DateTime.Now.Minute;
                    }
                    else if (type == admin_const.E_IMG_TYPE.ARTICLE)
                    {
                        imagePathTemp = "article/" +
                            DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/" +
                           DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Year + DateTime.Now.Hour + DateTime.Now.Minute;
                    }
                    else if (type == admin_const.E_IMG_TYPE.PRODUCT)
                    {
                        imagePathTemp = "product/" +
                            DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/" +
                           DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Year + DateTime.Now.Hour + DateTime.Now.Minute;
                    }
                    else if (type == admin_const.E_IMG_TYPE.PRODUCT_IMG)
                    {
                        //anh cua sp lam hoi khac 1 ti :)
                        imagePathTemp = "productimg/" +
                            DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/" + cur_name;// +
                        //DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Year + DateTime.Now.Hour + DateTime.Now.Minute;
                    }
                    else if (type == admin_const.E_IMG_TYPE.PAGE_STATIC)
                    {
                        imagePathTemp = "page/" +
                            DateTime.Now.Year.ToString() + "/" + DateTime.Now.Month.ToString() + "/" +
                           DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Year + DateTime.Now.Hour + DateTime.Now.Minute;
                    }
                    else if (type == admin_const.E_IMG_TYPE.WEB_LINK)
                    {
                        imagePathTemp = "link/" +
                           DateTime.Now.Day + DateTime.Now.Month + DateTime.Now.Year + DateTime.Now.Hour + DateTime.Now.Minute;
                    }
                    else if (type == admin_const.E_IMG_TYPE.PARTNER)
                    {
                        imagePathTemp = "partner/";
                    }
                    retimg = string.Format("/images/{0}{1}", imagePathTemp, control.FileName);
                    var strPhysicalApplicationPath = siteSettingSingleModels.GetConfig(global_const.STORAGE_CONFIG); //HttpContext.Current.Request.PhysicalApplicationPath 

                    //delete old image if updating
                    if (!string.IsNullOrEmpty(cur_name) && is_del == true)//lblAnh.Text != "&nbsp;" && 
                    {
                        string strImg = cur_name;
                        //strImg = strImg.Replace("<img src='", "");
                        // strImg = strImg.Replace("' style='width:100px;height:100px'/>", "");
                        Ufile.DelFileWithLocation(strPhysicalApplicationPath + strImg.Replace("/", "\\"));
                    }

                    //upload image  & create folder if need
                    string RealFile = strPhysicalApplicationPath + retimg.Replace("/", "\\");
                    //string virtualFolder = "~/" + imagePath.Substring(0, imagePath.LastIndexOf('/') + 1);
                    //string folder = HttpContext.Current.Server.MapPath(virtualFolder);
                    string folder = RealFile.Substring(0, RealFile.LastIndexOf('\\') + 1);
                    if (!Directory.Exists(folder))
                        Directory.CreateDirectory(folder);
                    control.SaveAs(RealFile);
                    //lblAnh.Text = LoadImage(imagePath);
                }
                else if (string.IsNullOrEmpty(cur_name))
                    retimg = "";
                else
                    retimg = cur_name;
                return retimg;
            }
            catch (Exception ex)
            {
                // ViewBag.result = false;
                //return ex.Message;
                return "";
            }
        }

        //delete file like: /image/file.jpg
        public static void DeleteFile(string vitual_path)
        {
            var strPhysicalApplicationPath = siteSettingSingleModels.GetConfig(global_const.STORAGE_CONFIG); //HttpContext.Current.Request.PhysicalApplicationPath 
            Ufile.DelFileWithLocation(strPhysicalApplicationPath + vitual_path.Replace("/", "\\"));
        }

        #endregion
        
        #region  controller managerment
        //lay ten controller
        public string ControllerName
        {
            get
            {
                return Url.RequestContext.RouteData.Values["controller"].ToString();
            }
        }
        //lay ten action
        public string ActionName
        {
            get
            {
                return Url.RequestContext.RouteData.Values["action"].ToString();
            }
        }
        // lay action cha cua children action
        public string ParentActionName
        {
            get
            {
                return ControllerContext.ParentActionViewContext.RouteData.Values["action"].ToString();
            }
        }
        #endregion

        #region send email bussiness
        //gui email di cho khach hang, su dung content trong DB
        public bool SendWebEmail(int mailId, List<EmailVariable> lstVarial, string emailTo, string strBcc, string strCc)
        {
            //lay thong tin cau hinh email server
            var SMTPPASS = siteSettingSingleModels.GetConfig(global_const.SMTPPASS);
            var SMTPPORT = int.Parse(siteSettingSingleModels.GetConfig(global_const.SMTPPORT));
            var SMTPUSER = siteSettingSingleModels.GetConfig(global_const.SMTPUSER);
            var SMTPHOST = siteSettingSingleModels.GetConfig(global_const.SMTPHOST);

            //lay content mail 
            var emailTemp = emailTemplateModels.getByID(mailId);
            if (emailTemp != null)
            {
                //ko cho email trong
                if (string.IsNullOrEmpty(emailTemp.email_content))
                    return false;

                var emailName = Ucommon.GetDefaultString(emailTemp.email_name, "ubuy.vn");
                var emailSubject = Ucommon.GetDefaultString(emailTemp.email_subject, "Email từ ubuy.vn");
                var emailContent = emailTemp.email_content;

                //replace content
                if (lstVarial.Count > 0)
                {
                    foreach (var variable in lstVarial)
                    {
                        emailContent = emailContent.Replace(string.Format("##{0}##", variable.key), variable.value);
                    }
                }
                //send email
                var emailobj = new email_component();
                return emailobj.SendEmail(emailTo, SMTPUSER, emailName, emailSubject, emailContent, SMTPHOST,
                                          SMTPPASS, SMTPUSER, SMTPPORT, strBcc, strCc);
            }
            return false;
        }
        #endregion

        // tao page: admin
        public void InitPage(ref bool permission)
        {
            ////check quyền tại đây
            if (Session["user_id"] != null)
            {
                int user_id = int.Parse(Session["user_id"].ToString());
                string path = "/" + ControllerName + "/" + ActionName;
                if (Models.accountModels.checkPageAccessByUser(user_id, path)){permission = true;}
                else { permission = false;}
            }
            else
            {
                HttpCookie ck = HttpContext.Request.Cookies["Sercurity_User"];
                if (ck != null)
                {
                    Session["user_id"] = ck.Values["user_id"];
                    int user_id = int.Parse(Session["user_id"].ToString());
                    string path = "/" + ControllerName + "/" + ActionName;
                    if (Models.accountModels.checkPageAccessByUser(user_id, path)) { permission = true; }
                    else { permission = false; }
                }
                else 
                {
                    Response.Redirect(Url.Action("login", "admAccount")); 
                }
            }
        }
        //kiem tra quyen member - public site
        public void IsMember()
        {
            ////check quyền tại đây
            if (Session["member_id"] != null)
            {
                int user_id = int.Parse(Session["member_id"].ToString());
                string path = "/" + ControllerName + "/" + ActionName;

                HttpCookie ck = HttpContext.Request.Cookies["Sercurity_User"];
                if (ck != null)
                {
                    Session["member_id"] = ck.Values["user_id"];
                    if (Models.accountModels.checkPageAccessByUser(user_id, path))
                    {
                        ViewBag.permission = true;
                    }
                    else
                    {
                        ViewBag.permission = false;// "You do not have permission to access...";
                    }
                }            
            }
            else
            {
                Response.Redirect(Url.Action("member_login","member"));
            }
        }
        //kiem tra number
        public bool isNumber(string val)
        {
            int Num;
            bool isNum = int.TryParse(val, out Num);
            if (isNum)
                return true;
            else
                return false;
        }
        
        //lay ra ten domain vd: ubuy.vn
        public string DefaultHostGetter()
        {
            string host = this.Request.Url.Host;
            if (host.Contains("www."))
            {
                host = host.Replace("www.", "");
            }
            return host;
        }        
        
        //lay ra language_code (vi) tren URL
        public string DefaultLanguageGetter()
        {
            return global_const.LANGUAGE_CODE_DEFAULT;
            /*
             * tam thoi khong dung
            var arr = this.Request.Url.PathAndQuery.Split('/');
            if (this.Request.Url.PathAndQuery.Contains("Rejected-By-UrlScan?~"))
            {
                arr = this.Request.Url.PathAndQuery.Replace("/Rejected-By-UrlScan?~", "").Split('/');
                return arr[0];
            }
            else
                return arr[1];
            */            
        }

        public string SourceGetter()
        {
            var arr = this.Request.Url.PathAndQuery.Split('/');
            if (this.Request.Url.PathAndQuery.Contains("Rejected-By-UrlScan?~"))
            {
                arr = this.Request.Url.PathAndQuery.Replace("/Rejected-By-UrlScan?~", "").Split('/');
                return "/" + arr[0] + "/";
            }
            else
                return "/" + arr[1] + "/";

        }
        /// <summary>
        /// Renders an action result to a string. This is done by creating a fake http context
        /// and response objects and have that response send the data to a string builder
        /// instead of the browser.
        /// </summary>
        /// <param name="result">The action result to be rendered to string.</param>
        /// <returns>The data rendered by the given action result.</returns>
        public string RenderActionResultToString(ActionResult result)
        {
            // Create memory writer.
            var sb = new StringBuilder();
            var memWriter = new StringWriter(sb);

            // Create fake http context to render the view.
            var fakeResponse = new HttpResponse(memWriter);
            var fakeContext = new HttpContext(System.Web.HttpContext.Current.Request, fakeResponse);
            var fakeControllerContext = new ControllerContext(
                new HttpContextWrapper(fakeContext),
                this.ControllerContext.RouteData,
                this.ControllerContext.Controller);
            var oldContext = System.Web.HttpContext.Current;
            System.Web.HttpContext.Current = fakeContext;

            // Render the view.
            result.ExecuteResult(fakeControllerContext);

            // Restore data.
            System.Web.HttpContext.Current = oldContext;

            // Flush memory and return output.
            memWriter.Flush();
            return sb.ToString();
        }

        //header admin
        [ChildActionOnly]
        public ActionResult control_header()
        {
            return PartialView("../Shared/control_header");
        }

        [ChildActionOnly]
        public ActionResult control_leftmenu_admin()
        {   
            var menu_view = new ViewModels.MenuAdminViewModels();
            menu_view.strMenu = accountModels.MenuBuilderAdmin(null, int.Parse(Session["user_id"].ToString()), Request.Url.ToString());
            menu_view.controller_name = ControllerName;
            return PartialView("../Shared/control_leftmenu_admin", menu_view);
        } 

        //tao thong tin metadata cho site
        public void base_metadata(MetadataViewModels metadata_view)
        {
            var strPageName = Uconfig.GetConfig(global_const.PAGE_NAME, global_const.LANGUAGE_CODE_DEFAULT);
            var strKeyword = Uconfig.GetConfig(global_const.KEYWORD, global_const.LANGUAGE_CODE_DEFAULT);
            var strDescription = Uconfig.GetConfig(global_const.DESCRIPTION, global_const.LANGUAGE_CODE_DEFAULT);
            var strPoweredBy = Uconfig.GetConfig(global_const.POWEREDBY, global_const.LANGUAGE_CODE_DEFAULT);
            var strdcCreator = Uconfig.GetConfig(global_const.DCCREATOR, global_const.LANGUAGE_CODE_DEFAULT);
            var strAuthor = Uconfig.GetConfig(global_const.AUTHOR, global_const.LANGUAGE_CODE_DEFAULT);
            var strrobots = Uconfig.GetConfig(global_const.ROBOTS, global_const.LANGUAGE_CODE_DEFAULT);
            var strlanguage = Uconfig.GetConfig(global_const.LANGUAGE, global_const.LANGUAGE_CODE_DEFAULT);
            var strcreated = Uconfig.GetConfig(global_const.CREATED, global_const.LANGUAGE_CODE_DEFAULT);
            var strmodified = Uconfig.GetConfig(global_const.MODIFIED, global_const.LANGUAGE_CODE_DEFAULT);
            var strrevisitAfter = Uconfig.GetConfig(global_const.REVISITAFTER, global_const.LANGUAGE_CODE_DEFAULT);
            var strdatePublichcation = Uconfig.GetConfig(global_const.DATEPUBLICHCATION, global_const.LANGUAGE_CODE_DEFAULT);
            var strhomePage = Uconfig.GetConfig(global_const.HOMEPAGE, global_const.LANGUAGE_CODE_DEFAULT);

            if (metadata_view!=null)
              {
                ViewData["title"] = string.IsNullOrEmpty(metadata_view.title) != true ? string.Format("{0} | {1}", metadata_view.title,strPageName) : strPageName ;
                ViewData["PoweredBy"] = string.IsNullOrEmpty(metadata_view.PoweredBy) != true ? metadata_view.PoweredBy : strPoweredBy;
                ViewData["dcCreator"] = string.IsNullOrEmpty(metadata_view.dcCreator) != true ? metadata_view.dcCreator : strdcCreator;
                ViewData["Author"] = string.IsNullOrEmpty(metadata_view.Author) != true ? metadata_view.Author : strAuthor;
                ViewData["robots"] = string.IsNullOrEmpty(metadata_view.robots) != true ? metadata_view.robots : strrobots;
                ViewData["description"] = string.IsNullOrEmpty(metadata_view.description) != true ? metadata_view.description : strDescription;
                ViewData["keyword"] = string.IsNullOrEmpty(metadata_view.keyword) != true ? metadata_view.keyword : strKeyword;
                ViewData["language"] = string.IsNullOrEmpty(metadata_view.language) != true ? metadata_view.language : strlanguage;
                ViewData["created"] = string.IsNullOrEmpty(metadata_view.created) != true ? metadata_view.created : strcreated;
                ViewData["modified"] = string.IsNullOrEmpty(metadata_view.modified) != true ? metadata_view.modified : strmodified;
                ViewData["revisitAfter"] = string.IsNullOrEmpty(metadata_view.revisitAfter) != true ? metadata_view.revisitAfter : strrevisitAfter;
                ViewData["datePublichcation"] = string.IsNullOrEmpty(metadata_view.datePublichcation) != true ? metadata_view.datePublichcation : strdatePublichcation;
                ViewData["homePage"] = string.IsNullOrEmpty(metadata_view.homePage) != true ? metadata_view.homePage : strhomePage;
                }
             else {
                //default 
                ViewData["title"] = strPageName;
                ViewData["PoweredBy"] = strPoweredBy;
                ViewData["dcCreator"] = strdcCreator;
                ViewData["Author"] = strAuthor;
                ViewData["robots"] = strrobots;
                ViewData["description"] = strDescription;
                ViewData["keyword"] = strKeyword;
                ViewData["language"] = strlanguage;
                ViewData["created"] = strcreated;
                ViewData["modified"] = strmodified;
                ViewData["revisitAfter"] = strrevisitAfter;
                ViewData["datePublichcation"] = strdatePublichcation;
                ViewData["homePage"] = strhomePage;
            }
        }

        public CaptchaImageResult ShowCaptchaImage()
        {
            return new CaptchaImageResult();
        }

        public ActionResult CheckEmailExists(string emailStr)
        {
            var re = accountModels.CheckEmailExists(emailStr);
            if (re) { return Json("1"); } else { return Json("0"); }
            
        }

    }
}
